package com.example.tms.controller;

import com.example.tms.bean.*;
import com.example.tms.mapper.*;
import com.example.tms.tools.GlobalParam;
import org.apache.catalina.mapper.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@RestController
public class CarController {

    private final CarMapper carMapper;
    private final CarVMapper carVMapper;
    private final DeptMapper deptMapper;
    private final FileMapper fileMapper;
    private final DriverMapper driverMapper;

    @Autowired
    public CarController(CarMapper carMapper, CarVMapper carVMapper,DeptMapper deptMapper, FileMapper fileMapper, DriverMapper driverMapper){
        this.carMapper = carMapper;
        this.carVMapper = carVMapper;
        this.deptMapper = deptMapper;
        this.fileMapper = fileMapper;
        this.driverMapper = driverMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询车辆信息列表兼搜索
    @RequestMapping(value = "car",method = RequestMethod.GET)
    public ReturnInfo getCarinfoAll(@RequestParam(required = false, defaultValue = "") String cph,
                                    @RequestParam(required = false, defaultValue = "") String zgcch,
                                    @RequestParam(required = false, defaultValue = "") String dabh,
                                    @RequestParam(required = false, defaultValue = "") String name){
        System.out.println("cph:"+cph+"  zgcch:"+zgcch+"  dabh:"+dabh+"  name:"+name);
        List<CarView> result = carVMapper.findAll((Root<CarView> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)->{
            List<Predicate> list = new ArrayList<>();
            if(!cph.equals("")){
                list.add(criteriaBuilder.like(root.get("cph").as(String.class), "%" + cph + "%"));
            }
            if(!zgcch.equals("")){
                list.add(criteriaBuilder.like(root.get("zgcch").as(String.class), "%" + zgcch + "%"));
            }
            if(!dabh.equals("")){
                list.add(criteriaBuilder.like(root.get("dabh").as(String.class), "%" + dabh + "%"));
            }
            if(!name.equals("")){
                list.add(criteriaBuilder.equal(root.get("name").as(String.class), name));
            }
            list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class),true));
            Predicate[] p = new Predicate[list.size()];
            criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("lasttime")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
    }

    //查询车辆信息
    @RequestMapping(value = "car/{clid}",method = RequestMethod.GET)
    public CarView getCarinfo(@PathVariable String clid){
        return carVMapper.findByClidAndSfcz(clid,true);
    }

    //新建车辆信息
    @RequestMapping(value = "car",method = RequestMethod.POST)
    public List<Map<String,Object>> saveCarinfo(@RequestBody CarInfo carInfo){
        List<Map<String,Object>>  list = new ArrayList<Map<String,Object>>();
        Map<String,Object>  map = new HashMap<String,Object>();
        if(carInfo.getCph().equals("")||!checkCph(carInfo.getCph())){
            map.put("cph", "0");
        }else if(carMapper.findByCphAndSfcz(carInfo.getCph(), true)!=null){
            map.put("cph", "2");//车牌号已存在
        }
        if(carInfo.getZgcch().equals("")||!checkZgcch(carInfo.getZgcch())){
            map.put("zgcch", "0");
        }
        if(carInfo.getBumenid()==null&& deptMapper.findByBumenid(carInfo.getBumenid())==null){
            map.put("bumenid", "0");
        }
        if(carInfo.getSfwjc()==null||!checkSfwjc(carInfo.getSfwjc())){
            map.put("sfwjc", "0");
        }
        if(!carInfo.getGcorjk().equals("")&&!checkGcorjk(carInfo.getGcorjk())){
            map.put("gcorjk", "0");
        }
        if(!carInfo.getZxxs().equals("")&&!checkZxxs(carInfo.getZxxs())){
            map.put("zxxs", "0");
        }
        if(!carInfo.getLtsl().equals("")&&!checkLtsl(carInfo.getLtsl())){
            map.put("ltsl", "0");
        }
        if(!carInfo.getFdjh().equals("")&&!checkFdjh(carInfo.getFdjh())){ //非必填项
            map.put("fdjh", "0");
        }
        if(!carInfo.getCjh().equals("")&&!checkCjh(carInfo.getCjh())){ //非必填项
            map.put("cjh", "0");
        }
        if(!carInfo.getFdjxh().equals("")&&!checkFdjxh(carInfo.getFdjxh())){ //非必填项
            map.put("fdjxh", "0");
        }
        if(!carInfo.getHdzk().equals("")&&!checkHdzk(carInfo.getHdzk())){ //非必填项
            map.put("hdzk", "0");
        }
        if(!carInfo.getJsszk().equals("")&&!checkJsszk(carInfo.getJsszk())){ //非必填项
            map.put("jsszk", "0");
        }
        if(!carInfo.getZhoushu().equals("")&&!checkZhoushu(carInfo.getZhoushu())){ //非必填项
            map.put("zhoushu", "0");
        }
        if(!carInfo.getYydw().equals("")&&!checkYydw(carInfo.getYydw())){ //非必填项
            map.put("yydw", "0");
        }
        if(!carInfo.getCzsj().equals("")&&!checkCzsj(carInfo.getCzsj())){ //非必填项
            map.put("czsj", "0");
        }
        if(!carInfo.getYyzfyj().equals("")&&fileMapper.findOne(carInfo.getYyzfyj())==null){
            map.put("yyzfyj","1");
        }
        if(!carInfo.getXszfyj().equals("")&&fileMapper.findOne(carInfo.getXszfyj())==null){
            map.put("xszfyj","1");
        }
        if(!carInfo.getDjzsfyj().equals("")&&fileMapper.findOne(carInfo.getDjzsfyj())==null){
            map.put("djzsfyj","1");
        }
        if(!carInfo.getCltp().equals("")&&fileMapper.findOne(carInfo.getCltp())==null){
            map.put("cltp","1");
        }
        list.add(map);
        if(map.isEmpty()){
            if(!carInfo.getYyzfyj().equals("")){
                fileMapper.updateCz(carInfo.getYyzfyj());
            }
            if(!carInfo.getXszfyj().equals("")){
                fileMapper.updateCz(carInfo.getXszfyj());
            }
            if(!carInfo.getDjzsfyj().equals("")){
                fileMapper.updateCz(carInfo.getDjzsfyj());
            }
            if(!carInfo.getCltp().equals("")){
                fileMapper.updateCz(carInfo.getCltp());
            }
            carInfo.setYkid("");
            carInfo.setSjid("");
            carInfo.setClzt("可用");
            carInfo.setLasttime(GlobalParam.getTime());
            carInfo.setSfcz(true);
            carMapper.save(carInfo);
            logger.info("新建车辆"+carInfo.toString());
        }
        return list;
    }

    //更新车辆信息
    @RequestMapping(value = "car",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateCarinfo(@RequestBody CarInfo carInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(carInfo.getClid()==null||carMapper.findByClid(carInfo.getClid())==null){
            map.put("clid", "0");//该车辆不存在
        }
        CarInfo oldcar = carMapper.findByClid(carInfo.getClid());
        if(!carInfo.getCph().equals(oldcar.getCph())&&carMapper.findByCphAndSfcz(carInfo.getCph(),true)!=null) {
            map.put("cph", "2");
        }else if(carInfo.getCph().equals("")||!checkCph(carInfo.getCph())){
            map.put("cph", "0");
        }
//        if(!carInfo.getYkh().equals(oldcar.getYkh())&&carMapper.findByYkhAndSfcz(carInfo.getYkh(),true)!=null) {
//            map.put("ykh", "2");
//        }else if(carInfo.getYkh().equals("")){
//            map.put("ykh", "0");
//        }
        if(carInfo.getZgcch().equals("")||!checkZgcch(carInfo.getZgcch())){
            map.put("zgcch", "0");
        }
        if(carInfo.getBumenid()==null&&deptMapper.findByBumenid(carInfo.getBumenid())==null){
            map.put("bumenid", "0");
        }
        if(carInfo.getSfwjc()==null||!checkSfwjc(carInfo.getSfwjc())){
            map.put("sfwjc", "0");
        }
        if(!carInfo.getGcorjk().equals("")&&!checkGcorjk(carInfo.getGcorjk())){
            map.put("gcorjk", "0");
        }
        if(!carInfo.getZxxs().equals("")&&!checkZxxs(carInfo.getZxxs())){
            map.put("zxxs", "0");
        }
        if(!carInfo.getLtsl().equals("")&&!checkLtsl(carInfo.getLtsl())){
            map.put("ltsl", "0");
        }
        if(!carInfo.getFdjh().equals("")&&!checkFdjh(carInfo.getFdjh())){ //非必填项
            map.put("fdjh", "0");
        }
        if(!carInfo.getCjh().equals("")&&!checkCjh(carInfo.getCjh())){ //非必填项
            map.put("cjh", "0");
        }
        if(!carInfo.getFdjxh().equals("")&&!checkFdjxh(carInfo.getFdjxh())){ //非必填项
            map.put("fdjxh", "0");
        }
        if(!carInfo.getHdzk().equals("")&&!checkHdzk(carInfo.getHdzk())){ //非必填项
            map.put("hdzk", "0");
        }
        if(!carInfo.getJsszk().equals("")&&!checkJsszk(carInfo.getJsszk())){ //非必填项
            map.put("jsszk", "0");
        }
        if(!carInfo.getZhoushu().equals("")&&!checkZhoushu(carInfo.getZhoushu())){ //非必填项
            map.put("zhoushu", "0");
        }
        if(!carInfo.getYydw().equals("")&&!checkYydw(carInfo.getYydw())){ //非必填项
            map.put("yydw", "0");
        }
        if(!carInfo.getCzsj().equals("")&&!checkCzsj(carInfo.getCzsj())){ //非必填项
            map.put("czsj", "0");
        }
        if(!carInfo.getYyzfyj().equals("")&&fileMapper.findOne(carInfo.getYyzfyj())==null){
            map.put("yyzfyj","1");
        }
        if(!carInfo.getXszfyj().equals("")&&fileMapper.findOne(carInfo.getXszfyj())==null){
            map.put("xszfyj","1");
        }
        if(!carInfo.getDjzsfyj().equals("")&&fileMapper.findOne(carInfo.getDjzsfyj())==null){
            map.put("djzsfyj","1");
        }
        if(!carInfo.getCltp().equals("")&&fileMapper.findOne(carInfo.getCltp())==null){
            map.put("cltp","1");
        }
        list.add(map);
        if(map.isEmpty()){
            if(!carInfo.getYyzfyj().equals("")&&!fileMapper.findOne(carInfo.getYyzfyj()).getSfcz()){
                fileMapper.updateCz(carInfo.getYyzfyj());
            }
            if(!carInfo.getXszfyj().equals("")&&!fileMapper.findOne(carInfo.getXszfyj()).getSfcz()){
                fileMapper.updateCz(carInfo.getXszfyj());
            }
            if(!carInfo.getDjzsfyj().equals("")&&!fileMapper.findOne(carInfo.getDjzsfyj()).getSfcz()){
                fileMapper.updateCz(carInfo.getDjzsfyj());
            }
            if(!carInfo.getCltp().equals("")&&!fileMapper.findOne(carInfo.getCltp()).getSfcz()){
                fileMapper.updateCz(carInfo.getCltp());
            }
            carInfo.setYkid("");
            carInfo.setSjid("");
            carInfo.setClzt("");

            carInfo.setLasttime(GlobalParam.getTime());
            carInfo.setSfcz(true);
            carMapper.saveAndFlush(carInfo);
            logger.info("车辆更新"+carInfo.toString());
        }
        return list;
    }

    //删除车辆信息（假删除 车辆id）
    @RequestMapping(value = "car/{clid}",method = RequestMethod.DELETE)
    public ReturnInfo deleteCarinfo(@PathVariable String clid){
        String b;
        if(clid==null||carMapper.findByClid(clid)==null){
            b = "该车辆不存在！";
        }else{
            carMapper.DeleteByClid(clid);
            b = "删除成功！";
        }
        logger.info("车辆删除"+clid);
        return ReturnInfo.info1(b);
    }








    //检查车辆状态格式
    private Boolean checkClzt(String clzt){
        Boolean b = false;
        if(clzt.equals("可用")||clzt.equals("已分配")||clzt.equals("配货")||clzt.equals("在途")||clzt.equals("修理")||clzt.equals("停运")||clzt.equals("报废")||clzt.equals("转出")){
            b = true;
        }
        return b;
    }

    //检查是否外叫车格式
    private Boolean checkSfwjc(String sfwjc){
        Boolean b = false;
        if(sfwjc.equals("是")||sfwjc.equals("否")){
            b = true;
        }
        return b;
    }

    //检查国产/进口格式
    private Boolean checkGcorjk(String gcorjk){
        Boolean b = false;
        if(gcorjk.equals("国产")||gcorjk.equals("进口")){
            b = true;
        }
        return b;
    }

    //检查转向形式格式
    private Boolean checkZxxs(String zxxs){
        Boolean b = false;
        if(zxxs.equals("方向盘")||zxxs.equals("无")){
            b = true;
        }
        return b;
    }

    //检查轮胎数量格式
    private Boolean checkLtsl(String ltsl){
        Boolean b = false;
        if(ltsl.equals("4*2")||ltsl.equals("6*4")||ltsl.equals("6*2")){
            b = true;
        }
        return b;
    }
    //检查车牌号格式
    private Boolean checkCph(String cph){
        Boolean b = false;
        if(cph.matches("^[冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领A-Z]{1}[a-zA-Z0-9]{5}[a-zA-Z0-9挂学警港澳]{1}$")){
            b = true;
        }
        return b;
    }
    //检查主(挂)车车号格式
    private Boolean checkZgcch(String zgcch){
        Boolean b = false;
        if(zgcch.matches("^[冀豫云辽黑湘皖鲁苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼渝京津沪新京军空海北沈兰济南广成使领A-Z]{1}[a-zA-Z0-9]{5}[a-zA-Z0-9挂学警港澳]{1}$")){
            b = true;
        }
        return b;
    }
    //检查发动机号格式
    private Boolean checkFdjh(String fdjh){
        Boolean b = false;
        if(fdjh.matches("^[\\da-zA-Z]{7,20}$")){
            b = true;
        }
        return b;
    }
    //检查发动机型号格式
    private Boolean checkFdjxh(String fdjxh){
        Boolean b = false;
        if(fdjxh.matches("^.{7,20}$")){
            b = true;
        }
        return b;
    }
    //检查车架号格式
    private Boolean checkCjh(String cjh){
        Boolean b = false;
        if(cjh.matches("^[a-zA-Z0-9]{11,20}$")){
            b = true;
        }
        return b;
    }
    //检查核定载客格式
    private Boolean checkHdzk(String hdzk){
        Boolean b = false;
        if(hdzk.matches("^\\d{1,3}$")){
            b = true;
        }
        return b;
    }
    //检查驾驶室载客格式
    private Boolean checkJsszk(String jsszk){
        Boolean b = false;
        if(jsszk.matches("^\\d{1,2}$")){
            b = true;
        }
        return b;
    }
    //检查轴数格式
    private Boolean checkZhoushu(String zhoushu){
        Boolean b = false;
        if(zhoushu.matches("^\\d{1,2}$")){
            b = true;
        }
        return b;
    }
    //检查营运吨位格式
    private Boolean checkYydw(String yydw){
        Boolean b = false;
        if(yydw.matches("^[0-9]+(.[0-9]{1,2})?$")){
            b = true;
        }
        return b;
    }
    //检查车载手机格式
    private Boolean checkCzsj(String  czsj){
        Boolean b = false;
        if(czsj.matches("^1[0-9 -]{1,20}$")){
            b = true;
        }
        return b;
    }
}


